package com.felipecsl.gifimageview.app;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

import android.util.Log;

public class ByteArrayHttpClient {
	private static final String TAG = "ByteArrayHttpClient";

	// private static OkHttpClient client = new OkHttpClient();

	public static byte[] get(final String urlString) {
		InputStream in = null;
		try {
			final String decodedUrl = URLDecoder.decode(urlString, "UTF-8");
			final URL url = new URL(decodedUrl);

			// final Request request = new Request.Builder().url(url).build();
			// final Response response = client.newCall(request).execute();
			in = url.openStream();
			return toByteArray(in);
		} catch (final MalformedURLException e) {
			Log.d(TAG, "Malformed URL", e);
		} catch (final OutOfMemoryError e) {
			Log.d(TAG, "Out of memory", e);
		} catch (final UnsupportedEncodingException e) {
			Log.d(TAG, "Unsupported encoding", e);
		} catch (final IOException e) {
			Log.d(TAG, "IO exception", e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (final IOException ignored) {
				}
			}
		}
		return null;
	}

	private static byte[] toByteArray(InputStream in) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int len = 0;
		byte[] b = new byte[1024];
		try {
			while ((len = in.read(b, 0, b.length)) != -1) {
				baos.write(b, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] buffer = baos.toByteArray();
		return buffer;
	}
}
